<template>
  <div class="container">
    <el-dialog
      title="添加订单"
      :visible.sync="addDialog.centerDialogVisible"
      @open="openData"
      @close="cancel"
      center
      width="99%"
    >
      <div class="top">
        <el-switch
          v-model="is_assign"
          active-text="批次出(成本价)"
          inactive-text="先入先出(平均价)"
          @change="onAssign"
        >
        </el-switch>
      </div>

      <el-select
        style="margin-bottom: 5px"
        v-model="organization"
        :multiple="false"
        filterable
        remote
        center
        reserve-keyword
        placeholder="请选择机构"
        :remote-method="organizationMethod"
        :loading="insides.loading"
      >
        <el-option
          v-for="item in insides.option"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <div class="top">
        <el-select
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          v-model="selectList"
          placeholder="请搜索选择配送中心"
          :remote-method="selectListsRemoteMethod"
          :loading="selectLists.loading"
          @change="distribution(selectList)"
        >
          <el-option
            v-for="item in selectLists.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="top">
        <el-select
          size="small"
          v-model="search.supplier_code"
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          placeholder="请选择供应商"
          :remote-method="supplierRemoteMethod"
          @change="supplierOn"
          :loading="supplierCenter.loading"
        >
          <el-option
            v-for="item in supplierCenter.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="top">
        <el-select
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          v-model="commodity"
          placeholder="请搜索选择商品"
          :remote-method="insideRemoteMethod"
          :loading="inside.loading"
        >
          <el-option
            v-for="item in inside.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-search"
          @click="addGoods()"
          >添加</el-button
        >
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-plus"
          v-if="is_assign && tableData.length > 0"
          @click="addReturn()"
          >获取到货价</el-button
        >
        <el-button
          size="medium"
          v-if="!is_assign"
          type="primary"
          class="handleSearch"
          icon="el-icon-upload"
          @click="download()"
          >模板下载</el-button
        >

        <el-upload
          v-if="!is_assign"
          class="upload-demo"
          style="display: inline; margin-left: 10px"
          action="#"
          :show-file-list="false"
          :http-request="handleAvatarSuccess"
        >
          <el-button
            size="medium"
            type="primary"
            class="handleSearch"
            icon="el-icon-circle-plus"
            >导入商品</el-button
          >
        </el-upload>
      </div>
      <div class="noList" v-if="noList">
        <p style="color: red">ERP不存在的商品：</p>
        <el-tag v-for="tag in tags" :key="tag.name">
          {{ tag.name }}
        </el-tag>
      </div>
      <el-table
        :data="tableData"
        border
        max-height="500"
        style="width: 100%"
        empty-text="暂无数据"
        :summary-method="getSummaries"
        show-summary
      >
        <el-table-column
          prop="goods_name"
          label="商品名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="erp_goods_code"
          label="商品编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goods_spec"
          label="规格"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="category_code"
          label="分类编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="category_name"
          label="分类名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goods_unit"
          label="单位"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="bar_code"
          label="条形码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="purchasePrice"
          v-if="!is_assign"
          label="采购加价"
          align="center"
        ></el-table-column>
        <el-table-column
          v-else
          prop="purchasePrices"
          label="采购加价"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="!is_assign"
          prop="avg_price"
          label="平均价"
          align="center"
        ></el-table-column>
        <el-table-column
          v-else
          prop="cost_price"
          label="成本价"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="!is_assign"
          prop="stockRemoval"
          label="出库价"
          align="center"
        ></el-table-column>
        <el-table-column
          v-else
          prop="stockRemovals"
          label="出库价"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="!is_assign"
          prop="totalPrices"
          label="出库价总价"
          align="center"
        ></el-table-column>
        <el-table-column
          v-else
          prop="totalPricess"
          label="出库价总价"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="!is_assign"
          prop="rk_spec"
          label="箱规"
          align="center"
        ></el-table-column>
        <el-table-column
          v-else
          prop="rk_specs"
          label="箱规"
          align="center"
        ></el-table-column>
        <el-table-column v-if="is_assign" label="生产日期" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.produce_date }}</p>
          </template>
        </el-table-column>
        <el-table-column v-if="is_assign" label="到期日" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.due_date }}</p>
          </template>
        </el-table-column>
        <el-table-column v-if="is_assign" label="保质期（天）" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.shelf_life }}</p>
          </template>
        </el-table-column>
        <el-table-column
          v-if="is_assign"
          label="批次商品"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.batch_id"
              placeholder="请选择批次商品"
              @change="onBatch(scope)"
            >
              <el-option
                v-for="item in scope.row.unAvgBatchList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :title="item.code"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <!-- <el-table-column label="供应商" align="center" width="150px">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.supplier_id"
              size="small"
              @change="getOptionId(scope.row.supplier_id, scope)"
              placeholder="请选择供应商"
            >
              <el-option
                v-for="item in scope.row.supplierList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column> -->
        <el-table-column
          v-if="is_assign"
          label="门店到货价"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="orderFixedPprice(scope)"
              :controls="false"
              v-model="scope.row.fixed_price"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="数量" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="orderNum(scope)"
              :controls="false"
              v-model="scope.row.order_num"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          v-if="!is_assign"
          label="加价"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="markup(scope)"
              :controls="false"
              v-model="scope.row.markup"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column v-else label="加价" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :disabled="scope.row.fixed_priceType"
              @change="markup(scope)"
              :controls="false"
              v-model="scope.row.markups"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="件数" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              @change="qtyup(scope)"
              size="small"
              :controls="false"
              v-model="scope.row.box_qty"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!is_assign"
          label="预提"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.withholding_fee }}</div>
          </template>
        </el-table-column>
        <el-table-column v-else label="预提" align="center" width="150px">
          <template slot-scope="scope">
            <div>{{ scope.row.withholding_fees }}</div>
          </template>
        </el-table-column>
        <el-table-column label="包装箱" align="center" width="150px">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.package_box_id"
              @change="rdcBox(scope)"
              placeholder="请选择"
            >
              <el-option
                v-for="item in boxList"
                :label="item.name"
                :key="item.id"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="包装箱规格" align="center" width="200px">
          <template slot-scope="scope">
            <div>
              <el-input-number
                size="small"
                :precision="4"
                v-if="scope.row.rdcType"
                :controls="false"
                v-model="scope.row.package_box_specInp"
              ></el-input-number>
              <span v-else>{{ scope.row.package_box_specInp }}</span>
              <span
                v-if="scope.row.rdcType"
                style="line-height: 30px;margin-left: 5px;"
                >KG</span
              >
              <span v-else style="line-height: 30px;margin-left: 5px;">个</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="250px">
          <template slot-scope="scope">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="scope.row.notes"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="danger"
              @click="remove(scope)"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addOrderInfo,
  selectErpOrderGoodsData,
  getUnAvgBatch,
  getFixedPrice,
  getPackageBoxData
} from "@/api/superOrderNew/superOrderList";
import { selectSupplierData } from "@/api/supplier/supplierList"; //供应商
import { getToken } from "@/utils/auth";
import { Loading } from "element-ui";
import { getOrgData } from "@/api/middleorder/middleorderlist";
import { getOpenOrgData } from "@/api/middleorder/middleorderlist";

import { selectRdcData } from "@/api/select/select";
export default {
  props: {
    addDialog: Object
  },
  data() {
    return {
      disabled: true,
      tableData: [],
      unAvgBatchData: [],
      tags: [],
      commodity: "",
      is_assign: false,
      noList: false,
      boxData: {},
      boxList: [],
      rdc: null,
      package: {
        package_box_id: "",
        package_box_spec: ""
      },
      supplierCenter: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      inside: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      insides: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },

      search: {
        goods_code: "",
        org_code: "",
        supplier_code: ""
      },
      organization: "",
      priceNum: 0,
      selectLists: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },

      selectList: "",
      distributionCenter: {
        warehouse_code: "",
        rdc_code: ""
      },
      fixed_priceType: false
    };
  },
  methods: {
    //取消
    cancel() {
      this.addDialog.centerDialogVisible = false;
      this.inside = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.insides = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.is_assign = false;
      this.commodity = "";
      this.organization = "";
      this.tableData = [];
      this.search = {
        goods_code: "",
        org_code: "",
        supplier_code: ""
      };
      this.selectLists = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.selectList = "";
      this.distributionCenter = {
        warehouse_code: "",
        rdc_code: ""
      };
      this.noList = false;
    },
    getPackageBox() {
      getPackageBoxData().then(res => {
        this.boxData = res.data.package;
        this.rdc = res.data.rdc;
      });
    },
    rdcBox(scope) {
      let id = scope.row.package_box_id;
      this.boxList.forEach((res, index) => {
        if (res.id == scope.row.package_box_id) {
          if (index == 0) {
            scope.row.rdcType = false;
            scope.row.package_box_specInp = 1;
          } else {
            scope.row.rdcType = true;
            scope.row.package_box_specInp = scope.row.package_box_spec;
          }
        }
      });
      console.log(scope.row.package_box_id, 9999);
    },

    // 嵌套搜索供应商数据
    supplierRemoteMethod(query) {
      if (query !== "") {
        this.getSupplier(query);
      } else {
        this.supplierCenter.option = [];
      }
    },
    getSupplier(name = "") {
      let data = {
        page: 1,
        limit: 100,
        name
      };
      //获取供应商列表
      selectSupplierData(data).then(res => {
        this.supplierCenter.option = res.data.paginate.data.map(item => {
          return {
            value: `${item.supplier_code}`,
            label: `${item.supplier_name}`
          };
        });
      });
    },
    // 供应商选择
    supplierOn() {
      this.tableData = [];
    },
    getData() {
      let data = {
        page: 1,
        limit: 500,
        goods_code: this.search.goods_code,
        rdc_code: this.distributionCenter.rdc_code,
        warehouse_code: this.distributionCenter.warehouse_code,
        is_can_use: 3
      };
      //获取商品
      selectErpOrderGoodsData(data).then(res => {
        this.goodsList = res.data.paginate.data;
        if (res.data.paginate.data) {
          this.inside.option = res.data.paginate.data.map(item => {
            return { value: `${item.Code}`, label: `${item.Name}` };
          });
        }
      });
    },
    //总价
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (index != 10) {
            sums[index] = "";
          } else {
            sums[index] = sums[index].toFixed(4);
          }
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    openData() {
      this.getDatas();
      this.getPackageBox();
      this.getselsetData();
      this.getSupplier();
    },
    getDatas() {
      let data = {
        page: 1,
        limit: 500,
        key: this.search.org_code
      };
      //获取机构
      getOpenOrgData(data).then(res => {
        if (res.data) {
          this.insides.option = res.data.map(item => {
            return { value: `${item.erp_org_code}`, label: `${item.name}` };
          });
        }
      });
    },
    getselsetData() {
      let data = {
        page: 1,
        limit: 500,
        code_or_name: this.search.selectnamecode
      };
      //获取配送中心
      selectRdcData(data).then(res => {
        if (res.data.paginate.data) {
          this.selectLists.option = res.data.paginate.data.map(item => {
            return {
              value: `${item.d_code}`,
              label: `${item.d_name}`,
              warehouse_code: `${item.warehouse_code}`,
              org_area_code: `${item.area_code}`,
              rdc_attr: `${item.rdc_attr}`
            };
          });
        }
      });
    },

    // 嵌套搜索配送方式数据
    selectListsRemoteMethod(query) {
      if (query !== "") {
        this.houseList(query);
      } else {
        this.selectLists.option = [];
      }
    },
    //获取配送数据
    houseList(query) {
      this.search.selectnamecode = query;
      this.getselsetData();
    },
    distribution(code) {
      let arr = this.selectLists.option.filter(res => {
        return res.value == code;
      });
      console.log(arr, 8888);
      if (arr[0].rdc_attr == "0") {
        this.boxList = this.boxData.shengnei;
      } else {
        this.boxList = this.boxData.shengwai;
      }

      this.distributionCenter = {
        warehouse_code: arr[0].warehouse_code,
        rdc_code: arr[0].value,
        org_area_code: arr[0].org_area_code
      };
      this.tableData = [];
      this.inside = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.commodity = "";
    },
    //修改加价率和预提
    markup(scope) {
      //先入先出计算
      let purchasePriceCenter = (
        Math.round(
          (parseFloat(scope.row.avg_price) +
            parseFloat(scope.row.withholding_fee) +
            parseFloat(scope.row.markup)) *
            parseFloat(scope.row.BuyerProfitRate) *
            10000
        ) / 10000
      ).toFixed(4);
      let purchasePriceCenters = (
        Math.round(
          (parseFloat(scope.row.cost_price) +
            parseFloat(scope.row.withholding_fees) +
            parseFloat(scope.row.markups)) *
            parseFloat(scope.row.BuyerProfitRate) *
            10000
        ) / 10000
      ).toFixed(4);
      scope.row.purchasePrice = scope.row.BuyerProfitMode
        ? scope.row.BuyerProfitRate
        : purchasePriceCenter;
      scope.row.purchasePrices = scope.row.BuyerProfitMode
        ? scope.row.BuyerProfitRate
        : purchasePriceCenters;
      scope.row.stockRemoval = (
        parseFloat(scope.row.avg_price) +
        parseFloat(scope.row.markup) +
        parseFloat(scope.row.withholding_fee) +
        parseFloat(scope.row.purchasePrice)
      ).toFixed(4);
      scope.row.totalPrices = (
        scope.row.stockRemoval * scope.row.order_num
      ).toFixed(4);
      this.$set(this.tableData, scope.$index, scope.row);
      //批次计算
      scope.row.stockRemovals = (
        parseFloat(scope.row.cost_price) +
        parseFloat(scope.row.markups) +
        parseFloat(scope.row.withholding_fees) +
        parseFloat(scope.row.purchasePrices)
      ).toFixed(4);
      scope.row.totalPricess = (
        scope.row.stockRemovals * scope.row.order_num
      ).toFixed(4);
      this.$set(this.tableData, scope.$index, scope.row);
    },
    //修改数量
    orderNum(scope) {
      if (this.is_assign) {
        if (scope.row.rk_specs) {
          let rk_specs = parseFloat(scope.row.rk_specs);
          scope.row.box_qty = (scope.row.order_num / rk_specs).toFixed(4);
        }
      } else {
        if (scope.row.rk_spec) {
          scope.row.box_qty = (scope.row.order_num / scope.row.rk_spec).toFixed(
            4
          );
        }
      }

      scope.row.totalPrices = (
        scope.row.stockRemoval * scope.row.order_num
      ).toFixed(4);

      scope.row.totalPricess = (
        scope.row.stockRemovals * scope.row.order_num
      ).toFixed(4);

      this.$set(this.tableData, scope.$index, scope.row);
    },
    //修改件数
    qtyup(scope) {
      if (scope.row.rk_spec) {
        scope.row.order_num = (scope.row.box_qty * scope.row.rk_spec).toFixed(
          4
        );
      }
      if (this.is_assign) {
        if (scope.row.rk_specs) {
          let rk_specs = parseFloat(scope.row.rk_specs);
          scope.row.order_num = (
            scope.row.box_qty * scope.row.rk_specs
          ).toFixed(4);
        }
      }
    },
    //删除
    remove(scope) {
      let id = scope.row.erp_goods_code;
      this.tableData.forEach((res, index) => {
        if (res.erp_goods_code == id) {
          this.tableData.splice(index, 1);
        }
      });
      this.priceNum = 0;
    },
    // 添加商品
    addGoods() {
      if (this.commodity) {
        let every = this.tableData.filter(res => {
          return (
            res.Code == this.commodity || res.erp_goods_code == this.commodity
          );
        });
        if (every.length == 0) {
          let arr = this.goodsList.filter(res => {
            return res.Code == this.commodity;
          });

          this.pushData(arr[0]);
        } else {
          this.$message({
            type: "info",
            message: "该商品已添加"
          });
        }
      } else {
        this.$message({
          type: "info",
          message: "请选择商品"
        });
      }
    },

    // 获取商品方法
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //获取商品数据
    getSupplierList(query) {
      this.search.goods_code = query;
      this.getData();
    },
    // 嵌套搜索机构数据
    organizationMethod(query) {
      if (query !== "") {
        this.organizationList(query);
      } else {
        this.insides.option = [];
      }
    },
    //获取机构数据
    organizationList(query) {
      this.search.org_code = query;
      this.getDatas();
    },

    pushData(scope) {
      let data = {
        dccode: this.selectList,
        erp_goods_code: scope.Code,
        supplier_code: this.search.supplier_code
      };
      getUnAvgBatch(data)
        .then(res => {
          let unAvgBatchList = [];
          res.data.paginate.forEach(item => {
            let codeList = item.code.split(",");
            let codeStr =
              codeList.length > 1 ? codeList[0] + "..." : codeList[0];
            unAvgBatchList.push({
              value: `${item.id}`,
              label: `${item.goods_name}【${codeStr}】【生产日期:${
                item.produce_date ? item.produce_date : "无"
              }】(${item.stock_num}/${item.rk_spec})`,
              price: `${item.price}`,
              withholding_fee: `${item.withholding_fee}`,
              markup_price: `${item.markup_price}`,
              rk_spec: `${item.rk_spec}`,
              code: `${item.code}`,
              produce_date: `${item.produce_date}`,
              shelf_life: `${item.shelf_life}`,
              due_date: `${item.due_date}`
            });
          });
          return unAvgBatchList;
        })
        .then(unAvgBatchList => {
          let rdcBool = null;
          if (this.rdc.length > 0) {
            rdcBool = this.rdc.some(res => {
              return res == this.distributionCenter.rdc_code;
            });
          }

          let cost_price = 0;
          let withholding_fees = 0;
          let purchasePriceCenter = (
            Math.round(
              (parseFloat(scope.avg_price) +
                parseFloat(scope.markup_price) +
                parseFloat(scope.withholding_fee)) *
                parseFloat(scope.BuyerProfitRate) *
                10000
            ) / 10000
          ).toFixed(4);
          let purchasePriceCenters = (
            Math.round(
              (parseFloat(cost_price) +
                parseFloat(scope.markup_price) +
                parseFloat(withholding_fees)) *
                parseFloat(scope.BuyerProfitRate) *
                10000
            ) / 10000
          ).toFixed(4);
          let purchasePrice = scope.BuyerProfitMode
            ? scope.BuyerProfitRate
            : purchasePriceCenter;
          let purchasePrices = scope.BuyerProfitMode
            ? scope.BuyerProfitRate
            : purchasePriceCenters;
          let stockRemoval = (
            parseFloat(scope.avg_price) +
            parseFloat(scope.markup_price) +
            parseFloat(scope.withholding_fee) +
            parseFloat(purchasePrice)
          ).toFixed(4);
          let stockRemovals = (
            parseFloat(cost_price) +
            parseFloat(withholding_fees) +
            parseFloat(purchasePrices)
          ).toFixed(4);
          this.tableData.push({
            erp_goods_code: scope.Code,
            goods_name: scope.Name,
            bar_code: scope.BarCode,
            goods_unit: scope.Unit,
            goods_spec: scope.Spec || "",
            category_code: scope.ClassCode,
            category_name: scope.ClassName,
            is_zc: 1,
            avg_price: scope.avg_price,
            cost_price: cost_price,
            stockRemoval: stockRemoval,
            stockRemovals: parseFloat(scope.fixed_price)
              ? scope.fixed_price
              : stockRemovals,
            fixed_priceType: parseFloat(scope.fixed_price) ? true : false,
            fixed_price: parseFloat(scope.fixed_price),
            purchasePrice: purchasePrice,
            purchasePrices: purchasePrices,
            BuyerProfitRate: scope.BuyerProfitRate,
            BuyerProfitMode: scope.BuyerProfitMode,
            totalPrices: 0,
            totalPricess: 0,
            total_price: 0,
            order_num: 0,
            box_qty: 0,
            package_box_id: rdcBool ? this.boxList[1].id : this.boxList[0].id,
            package_box_specInp: rdcBool ? scope.package_box_spec : 1,
            package_box_spec: scope.package_box_spec,
            rdcType: rdcBool ? true : false,
            withholding_fee: scope.withholding_fee,
            withholding_fees: withholding_fees,
            markup: scope.markup_price,
            markups: 0,
            batch_id: "",
            rk_spec: scope.rk_spec,
            rk_specs: 0,
            unAvgBatchList,
            notes: ""
          });
        });
    },

    //选择批次
    onBatch(scope) {
      scope.row.cost_price = this.batchPrice(
        scope.row.batch_id,
        scope.row.unAvgBatchList
      )[0];
      scope.row.withholding_fees = this.batchPrice(
        scope.row.batch_id,
        scope.row.unAvgBatchList
      )[1];
      let markup_price = this.batchPrice(
        scope.row.batch_id,
        scope.row.unAvgBatchList
      )[2];
      scope.row.rk_specs = this.batchPrice(
        scope.row.batch_id,
        scope.row.unAvgBatchList
      )[3];
      if (scope.row.rk_specs) {
        let rk_specs = parseFloat(scope.row.rk_specs);
        scope.row.box_qty = (scope.row.order_num / rk_specs).toFixed(4);
      }
      if (scope.row.fixed_priceType) {
        scope.row.stockRemovals = scope.row.fixed_price;
        if (!scope.row.BuyerProfitMode) {
          let num = (
            parseFloat(scope.row.fixed_price) /
            (1 + parseFloat(scope.row.BuyerProfitRate))
          ).toFixed(4);
          scope.row.purchasePrices = (
            parseFloat(scope.row.fixed_price) - num
          ).toFixed(4);
        } else {
          scope.row.purchasePrices = parseFloat(scope.row.BuyerProfitRate);
        }
        scope.row.markups = (
          parseFloat(scope.row.fixed_price) -
          parseFloat(scope.row.cost_price) -
          parseFloat(scope.row.withholding_fees) -
          parseFloat(scope.row.purchasePrices)
        ).toFixed(4);
        // scope.row.markups = (
        //   parseFloat(scope.row.fixed_price) -
        //   parseFloat(scope.row.withholding_fees) -
        //   parseFloat(scope.row.cost_price)
        // ).toFixed(4);
      } else {
        scope.row.markups = markup_price;
        let purchasePriceCenters = (
          Math.round(
            (parseFloat(scope.row.cost_price) +
              parseFloat(scope.row.withholding_fees) +
              parseFloat(scope.row.markups)) *
              parseFloat(scope.row.BuyerProfitRate) *
              10000
          ) / 10000
        ).toFixed(4);
        scope.row.purchasePrices = scope.row.BuyerProfitMode
          ? scope.row.BuyerProfitRate
          : purchasePriceCenters;
        scope.row.stockRemovals = (
          parseFloat(scope.row.cost_price) +
          parseFloat(scope.row.markups) +
          parseFloat(scope.row.withholding_fees) +
          parseFloat(scope.row.purchasePrices)
        ).toFixed(4);
      }
      scope.row.produce_date = this.batchPrice(
        scope.row.batch_id,
        scope.row.unAvgBatchList
      )[4];
      scope.row.shelf_life = this.batchPrice(
        scope.row.batch_id,
        scope.row.unAvgBatchList
      )[5];
      scope.row.due_date = this.batchPrice(
        scope.row.batch_id,
        scope.row.unAvgBatchList
      )[6];
      scope.row.totalPricess = (
        scope.row.stockRemovals * scope.row.order_num
      ).toFixed(4);
    },
    batchPrice(id, unAvgBatchList) {
      let price = 0;
      let withholding_fee = 0;
      let markup_price = 0;
      let rk_specs = 0;
      let produce_date = "";
      let shelf_life = "";
      let due_date = "";
      unAvgBatchList.forEach(res => {
        if (res.value == id) {
          price = res.price;
          withholding_fee = res.withholding_fee;
          markup_price = res.markup_price;
          rk_specs = res.rk_spec;
          produce_date = res.produce_date;
          shelf_life = res.shelf_life;
          due_date = res.due_date;
        }
      });
      return [
        price,
        withholding_fee,
        markup_price,
        rk_specs,
        produce_date,
        shelf_life,
        due_date
      ];
    },
    onAssign() {
      this.tableData.forEach(scope => {
        if (this.is_assign) {
          let rk_specs = parseFloat(scope.rk_specs);
          if (rk_specs) {
            scope.box_qty = (scope.order_num / rk_specs).toFixed(4);
          } else {
            scope.box_qty = 0;
          }
        } else {
          let rk_spec = parseFloat(scope.rk_spec);
          if (rk_spec) {
            scope.box_qty = (scope.order_num / rk_spec).toFixed(4);
          }
        }
        if (scope.fixed_priceType) {
          scope.stockRemovals = scope.fixed_price;
          if (!scope.BuyerProfitMode) {
            let num = (
              parseFloat(scope.fixed_price) /
              (1 + parseFloat(scope.BuyerProfitRate))
            ).toFixed(4);
            scope.purchasePrices = (
              parseFloat(scope.fixed_price) - num
            ).toFixed(4);
          } else {
            scope.purchasePrices = parseFloat(scope.BuyerProfitRate);
          }
          scope.markups = (
            parseFloat(scope.fixed_price) -
            parseFloat(scope.cost_price) -
            parseFloat(scope.withholding_fees) -
            parseFloat(scope.purchasePrices)
          ).toFixed(4);
          scope.totalPrices = (scope.stockRemoval * scope.order_num).toFixed(4);
          scope.totalPricess = (scope.stockRemovals * scope.order_num).toFixed(
            4
          );
        } else {
          scope.fixed_price = 0;
          let purchasePriceCenters = (
            Math.round(
              (parseFloat(scope.cost_price) +
                parseFloat(scope.markups) +
                parseFloat(scope.withholding_fees)) *
                parseFloat(scope.BuyerProfitRate) *
                10000
            ) / 10000
          ).toFixed(4);
          scope.purchasePrices = scope.BuyerProfitMode
            ? scope.BuyerProfitRate
            : purchasePriceCenters;
          scope.stockRemovals = (
            parseFloat(scope.cost_price) +
            parseFloat(scope.markups) +
            parseFloat(scope.withholding_fees) +
            parseFloat(scope.purchasePrices)
          ).toFixed(4);
          scope.totalPrices = (scope.stockRemoval * scope.order_num).toFixed(4);
          scope.totalPricess = (scope.stockRemovals * scope.order_num).toFixed(
            4
          );
        }
      });
    },
    //修改门店到货价
    orderFixedPprice(scope) {
      if (parseFloat(scope.row.fixed_price)) {
        scope.row.fixed_priceType = true;
        scope.row.stockRemovals = scope.row.fixed_price;
        if (!scope.row.BuyerProfitMode) {
          let num = (
            parseFloat(scope.row.fixed_price) /
            (1 + parseFloat(scope.row.BuyerProfitRate))
          ).toFixed(4);
          scope.row.purchasePrices = (
            parseFloat(scope.row.fixed_price) - num
          ).toFixed(4);
        } else {
          scope.row.purchasePrices = parseFloat(scope.row.BuyerProfitRate);
        }
        scope.row.markups = (
          parseFloat(scope.row.fixed_price) -
          parseFloat(scope.row.cost_price) -
          parseFloat(scope.row.withholding_fees) -
          parseFloat(scope.row.purchasePrices)
        ).toFixed(4);
        // scope.row.purchasePrices = 0;
        // scope.row.markups = (
        //   parseFloat(scope.row.fixed_price) -
        //   parseFloat(scope.row.withholding_fees) -
        //   parseFloat(scope.row.cost_price)
        // ).toFixed(4);
        scope.row.totalPrices = (
          scope.row.stockRemoval * scope.row.order_num
        ).toFixed(4);

        scope.row.totalPricess = (
          scope.row.stockRemovals * scope.row.order_num
        ).toFixed(4);
      } else {
        scope.row.fixed_priceType = false;
        // scope.row.fixed_price = 0;
        // let purchasePriceCenters = (
        //   Math.round(
        //     (parseFloat(scope.row.cost_price) +
        //       parseFloat(scope.row.withholding_fees) +
        //       parseFloat(scope.row.markup)) *
        //       parseFloat(scope.row.BuyerProfitRate) *
        //       10000
        //   ) / 10000
        // ).toFixed(4);
        // scope.row.purchasePrices = scope.row.BuyerProfitMode
        //   ? scope.row.BuyerProfitRate
        //   : purchasePriceCenters;
        // scope.row.stockRemovals = (
        //   parseFloat(scope.row.cost_price) +
        //   parseFloat(scope.row.markup) +
        //   parseFloat(scope.row.withholding_fees) +
        //   parseFloat(scope.row.purchasePrices)
        // ).toFixed(4);
        // scope.row.totalPrices = (
        //   scope.row.stockRemoval * scope.row.order_num
        // ).toFixed(4);
        // scope.row.totalPricess = (
        //   scope.row.stockRemovals * scope.row.order_num
        // ).toFixed(4);
      }
    },

    //导入商品
    handleAvatarSuccess(param) {
      let loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)"
      });
      let data = new window.FormData();
      data.append("goods_file", param.file);
      data.append("token", getToken());
      data.append("supplier_code", this.search.supplier_code);
      data.append("rdc_code", this.distributionCenter.rdc_code);
      data.append("warehouse_code", this.distributionCenter.warehouse_code);
      this.$axios.post("/smkapi/Norder/importOrderGoods", data).then(res => {
        loading.close();
        if (res.data.code == 0) {
          if (res.data.data.tips.length > 0) {
            res.data.data.tips.forEach(item => {
              this.tags.push({
                name: `${item.goods_name}(${item.goods_code})`
              });
            });
            this.noList = true;
          }
          this.$message({
            message: res.data.message || res.data.msg,
            type: "success"
          });
          this.tableData = [];
          res.data.data.list.forEach(scope => {
            let unAvgBatchList = [];
            scope.batch_list.forEach(item => {
              let codeList = item.code.split(",");
              let codeStr =
                codeList.length > 1 ? codeList[0] + "..." : codeList[0];
              unAvgBatchList.push({
                value: `${item.id}`,
                label: `${item.goods_name}【${codeStr}】【生产日期:${
                  item.produce_date ? item.produce_date : "无"
                }】(${item.stock_num}/${item.rk_spec})`,
                price: `${item.price}`,
                withholding_fee: `${item.withholding_fee}`,
                markup_price: `${item.markup}`,
                rk_spec: `${item.rk_spec}`,
                code: `${item.code}`,
                produce_date: `${item.produce_date}`,
                shelf_life: `${item.shelf_life}`,
                due_date: `${item.due_date}`
              });
            });
            let cost_price = 0;
            let withholding_fees = 0;
            let purchasePriceCenter = (
              Math.round(
                (parseFloat(scope.avg_price) +
                  parseFloat(scope.markup) +
                  parseFloat(scope.withholding_fee)) *
                  parseFloat(scope.BuyerProfitRate) *
                  10000
              ) / 10000
            ).toFixed(4);
            let purchasePriceCenters = (
              Math.round(
                (parseFloat(cost_price) +
                  parseFloat(scope.markup) +
                  parseFloat(withholding_fees)) *
                  parseFloat(scope.BuyerProfitRate) *
                  10000
              ) / 10000
            ).toFixed(4);
            let purchasePrice = scope.BuyerProfitMode
              ? scope.BuyerProfitRate
              : purchasePriceCenter;
            let purchasePrices = scope.BuyerProfitMode
              ? scope.BuyerProfitRate
              : purchasePriceCenters;
            let stockRemoval = (
              parseFloat(scope.avg_price) +
              parseFloat(scope.markup) +
              parseFloat(scope.withholding_fee) +
              parseFloat(purchasePrice)
            ).toFixed(4);
            let stockRemovals = (
              parseFloat(cost_price) +
              parseFloat(scope.markup) +
              parseFloat(withholding_fees) +
              parseFloat(purchasePrices)
            ).toFixed(4);
            let rdcBool = null;
            if (this.rdc.length > 0) {
              rdcBool = this.rdc.some(res => {
                return res == this.distributionCenter.rdc_code;
              });
            }
            this.tableData.push({
              BuyerProfitMode: scope.BuyerProfitMode,
              BuyerProfitRate: scope.BuyerProfitRate,
              erp_goods_code: scope.Code,
              goods_name: scope.Name,
              bar_code: scope.BarCode,
              goods_unit: scope.Unit,
              goods_spec: scope.Spec || "",
              category_code: scope.ClassCode,
              category_name: scope.ClassName,
              is_zc: 1,
              avg_price: scope.avg_price,
              cost_price: cost_price,
              stockRemoval: stockRemoval,
              stockRemovals: stockRemovals,
              fixed_priceType: parseFloat(scope.fixed_price) ? true : false,
              fixed_price: scope.fixed_price,
              purchasePrice: purchasePrice,
              purchasePrices: purchasePrices,
              rk_spec: scope.rk_spec,
              rk_specs: 0,
              package_box_id: rdcBool ? this.boxList[1].id : this.boxList[0].id,
              package_box_specInp: rdcBool ? scope.package_box_spec : 1,
              package_box_spec: scope.package_box_spec,
              rdcType: rdcBool ? true : false,
              totalPrices: (
                parseFloat(stockRemoval) * parseFloat(scope.order_num)
              ).toFixed(4),
              totalPricess: (
                parseFloat(stockRemovals) * parseFloat(scope.order_num)
              ).toFixed(4),
              total_price: 0,
              order_num: scope.order_num,
              box_qty: scope.box_qty,
              withholding_fee: scope.withholding_fee,
              withholding_fees: withholding_fees,
              markup: scope.markup,
              markups: scope.markup,
              notes: scope.notes,
              batch_id: "",
              unAvgBatchList
            });
          });
        } else {
          this.$message({
            type: "info",
            message: res.data.message || res.data.msg
          });
        }
      });
    },
    //下载模板
    download() {
      this.$confirm("是否下载模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/Norder/downloadTemplte?token=" +
            getToken();
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //获取到货价
    addReturn() {
      let codeList = [];
      this.tableData.forEach(prop => {
        codeList.push(prop.erp_goods_code);
      });
      let data = {
        erp_goods_codes: codeList.join(","),
        org_area_code: this.distributionCenter.org_area_code
      };
      getFixedPrice(data).then(res => {
        if (JSON.stringify(res.data.fixed_price_list)) {
          for (var i in res.data.fixed_price_list) {
            this.tableData.forEach(prop => {
              if (i == prop.erp_goods_code) {
                prop.fixed_price = res.data.fixed_price_list[i];
                let scope = {};
                scope.row = prop;
                this.orderFixedPprices(scope);
              }
            });
          }
        }
      });
    },
    //获取取门店到货价并修改
    orderFixedPprices(scope) {
      if (parseFloat(scope.row.fixed_price)) {
        scope.row.fixed_priceType = true;
        scope.row.stockRemovals = scope.row.fixed_price;
        if (!scope.row.BuyerProfitMode) {
          let num = (
            parseFloat(scope.row.fixed_price) /
            (1 + parseFloat(scope.row.BuyerProfitRate))
          ).toFixed(4);
          scope.row.purchasePrices = (
            parseFloat(scope.row.fixed_price) - num
          ).toFixed(4);
        } else {
          scope.row.purchasePrices = parseFloat(scope.row.BuyerProfitRate);
        }
        scope.row.markups = (
          parseFloat(scope.row.fixed_price) -
          parseFloat(scope.row.cost_price) -
          parseFloat(scope.row.withholding_fees) -
          parseFloat(scope.row.purchasePrices)
        ).toFixed(4);
        // scope.row.purchasePrices = 0;
        // scope.row.markups = (
        //   parseFloat(scope.row.fixed_price) -
        //   parseFloat(scope.row.withholding_fees) -
        //   parseFloat(scope.row.cost_price)
        // ).toFixed(4);
        scope.row.totalPrices = (
          scope.row.stockRemoval * scope.row.order_num
        ).toFixed(4);

        scope.row.totalPricess = (
          scope.row.stockRemovals * scope.row.order_num
        ).toFixed(4);
      } else {
        scope.row.fixed_priceType = false;
        // scope.row.fixed_price = 0;
        // let purchasePriceCenters = (
        //   Math.round(
        //     (parseFloat(scope.row.cost_price) +
        //       parseFloat(scope.row.withholding_fees) +
        //       parseFloat(scope.row.markup)) *
        //       parseFloat(scope.row.BuyerProfitRate) *
        //       10000
        //   ) / 10000
        // ).toFixed(4);
        // scope.row.purchasePrices = scope.row.BuyerProfitMode
        //   ? scope.row.BuyerProfitRate
        //   : purchasePriceCenters;
        // scope.row.stockRemovals = (
        //   parseFloat(scope.row.cost_price) +
        //   parseFloat(scope.row.markup) +
        //   parseFloat(scope.row.withholding_fees) +
        //   parseFloat(scope.row.purchasePrices)
        // ).toFixed(4);
        // scope.row.totalPrices = (
        //   scope.row.stockRemoval * scope.row.order_num
        // ).toFixed(4);
        // scope.row.totalPricess = (
        //   scope.row.stockRemovals * scope.row.order_num
        // ).toFixed(4);
      }
    },
    //确定
    confirm() {
      if (this.organization == "") {
        this.$message({
          type: "info",
          message: "请选择机构"
        });
      } else if (this.selectList == "") {
        this.$message({
          type: "info",
          message: "请选择配送中心"
        });
      } else if (this.tableData.length == "") {
        this.$message({
          type: "info",
          message: "请添加商品"
        });
      } else {
        let arr = [];

        this.tableData.forEach(res => {
          if (this.is_assign) {
            arr.push({
              erp_goods_code: res.erp_goods_code,
              goods_name: res.goods_name,
              bar_code: res.bar_code,
              goods_unit: res.goods_unit,
              goods_spec: res.goods_spec || "",
              category_code: res.category_code,
              category_name: res.category_name,
              is_zc: 1,
              cost_price: res.cost_price,
              order_num: res.order_num,
              box_qty: res.box_qty,
              withholding_fee: res.withholding_fees,
              markup: res.markups,
              batch_id: res.batch_id,
              fixed_price: res.fixed_price,
              buyerprofitmode: res.BuyerProfitMode,
              buyerprofitrate: res.BuyerProfitRate,
              rk_spec: res.rk_specs,
              package_box_id: res.package_box_id,
              package_box_spec: res.package_box_specInp,
              // produce_date: res.produce_date,
              // shelf_life: res.shelf_life,
              // due_date: res.due_date,
              notes: res.notes
            });
          } else {
            arr.push({
              erp_goods_code: res.erp_goods_code,
              goods_name: res.goods_name,
              bar_code: res.bar_code,
              goods_unit: res.goods_unit,
              goods_spec: res.goods_spec || "",
              category_code: res.category_code,
              category_name: res.category_name,
              is_zc: 1,
              order_num: res.order_num,
              box_qty: res.box_qty,
              withholding_fee: res.withholding_fee,
              markup: res.markup,
              buyerprofitmode: res.BuyerProfitMode,
              buyerprofitrate: res.BuyerProfitRate,
              rk_spec: res.rk_spec,
              package_box_id: res.package_box_id,
              package_box_spec: res.package_box_specInp,
              notes: res.notes
            });
          }
        });
        console.log(arr, 898989);
        let data = {
          is_assign: this.is_assign ? 1 : 0,
          erp_org_code: this.organization,
          goods: JSON.stringify(arr),
          dccode: this.selectList,
          supplier_code: this.search.supplier_code
        };
        addOrderInfo(data).then(res => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: res.msg || res.message
            });
            this.$emit("upData");
            this.cancel();
          }
        });
      }
    }
  }
};
</script>
<style scoped>
.pagination {
  text-align: right;
  padding: 10px;
}

.top {
  margin-bottom: 5px;
}

.noList {
  margin: 10px 0;
}
</style>
